﻿using System;
using System.Security.Principal;

namespace negoserverjni
{
    public class User
    {
        bool _isAuthenticated;
        bool[] presents;
        string name;
        string authenticationType;

        public User(WindowsIdentity winid,SecurityIdentifier[] sids ): this (winid, sids, true)
        {}

        public User(WindowsIdentity winid, SecurityIdentifier[] sids, bool WithAuthenticationType)
        {
            if (!Authenticated(winid)) return;
            _isAuthenticated = true;
            presents = Compare(GroupsOfUser(winid), sids);
            name = winid.Name;
            if (WithAuthenticationType) authenticationType = winid.AuthenticationType;
        }


        public bool[] IsMemberOfGroups()
        {
            return presents;
        }
        public bool IsAuthenticated
        { get { return _isAuthenticated; } }
        
        bool IsMemberOf(WindowsIdentity ide, SecurityIdentifier sid)
        {
            if (sid == null) return false;
            return true;
        }
        IdentityReferenceCollection GroupsOfUser(WindowsIdentity id)
        {
            if (id == null) return null;
            return id.Groups;
        }
        bool[] Compare(IdentityReferenceCollection identities, SecurityIdentifier[] sids)
        {
            if (sids == null) return null;
            bool[] result = new bool[sids.Length];

            for (int i = 0; i < sids.Length; i++)
            {
                result[i] = false;
                SecurityIdentifier sidGrp = sids[i];
                if (sidGrp == null) continue;
                foreach (IdentityReference id in identities)
                {
                    SecurityIdentifier ids = id as SecurityIdentifier;
                    if (sidGrp.Equals(ids))
                    {
                        result[i] = true;
                        break;
                    }
                }
            }
            return result;
        }
        bool Authenticated(WindowsIdentity winident)
        {
            foreach (IdentityReference id in winident.Groups)
            {
                SecurityIdentifier sid = id as SecurityIdentifier;
                if (sid != null)
                {
                    if (sid.IsWellKnown(WellKnownSidType.AuthenticatedUserSid)) return true;
                }
            }
            return false;            
        }
        public string Name
        { get { return name; } }

        public string AuthenticationType
        { get { return authenticationType; } }

    }
}
